window.addEventListener('load', function() {
  var log = console.log || window.console.log;
  var $ = document.querySelector.bind(document);

  var box = $('.box'); // 包裹住移动盒子的外层盒子dom
  var box1 = $('.box1'); // 被拖动的盒子dom
  var bar = $('.bar'); // 滚动条外层盒子dom
  var bar1 = $('.bar1'); // 滚动条dom

  var ex; //鼠标点击box1的初始位置
  var bl; //box1的初始left值
  var bo; //bar1的初始left值

  box1.onmousedown = function(e) {
    e.preventDefault();
    bl = box1.offsetLeft;
    bo = bar1.offsetLeft;
    ex = e.clientX;
    box1.style.cursor = 'move';
    box1.onmousemove = function(e) {
      if(bl + e.clientX - ex >= 0) {
        box1.style.left = 0;
        bar1.style.left = 0;
      } else if(bl + e.clientX - ex <= box.offsetWidth - box1.offsetWidth) {
        box1.style.left = box.offsetWidth - box1.offsetWidth + 'px';
        bar1.style.left = bar.offsetWidth - bar1.offsetWidth + 'px';
      } else {
        box1.style.left = bl + e.clientX - ex + 'px';
        bar1.style.left = bo + (bar.offsetWidth - bar1.offsetWidth)*(e.clientX - ex)/(box.offsetWidth - box1.offsetWidth) + 'px';
      }
    }
    document.onmouseup = function() {
      box1.onmousemove = null;
    }
  }

})